<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Api\MiniProgramController;

class LoginController extends Controller
{

    /**
     * 用户微信授权登录     todo  获取用户微信绑定手机号
     * @param Request $request
     * @return JsonResponse
     */
    function login(Request $request): JsonResponse {
        $request->validate([
            'code'   =>  'required|string',
            'pid'    =>  'sometimes|exists:users,id'
        ]);
        $mini_controller = new MiniProgramController();
        $login_res = $mini_controller->code2session($request->post('code'));
        //生成用户token
        $api_token = md5($login_res['openid'] . time());
        if ($login_res['status_code'] == 0) {//授权成功
            Log::info("info:".json_encode($login_res));
            //查询数据库中是否已经有该用户。没有创建，有则更新session_key
            $user = User::where('openid',$login_res['openid'])->first();
            if (!$user) {
                User::create([
                    'openid'        =>  $login_res['openid'],
                    'pid'           =>  $request->post('pid') ?? 0,
                    'session_key'   =>  $login_res['session_key'],
                    'api_token'     =>  $api_token,
                    'avatar'        =>  $request->post('avatarUrl',''),
                    'nickname'      =>  $request->post('nickName','')
                ]);
            } else {
                $user->avatar       =  $request->post('avatarUrl','');
                $user->nickname     =  $request->post('nickName','');
                $user->session_key  = $login_res['session_key'];
                $user->api_token    = $api_token;
                //该已存在用户没有上级并且传了要给他绑定的上级id时
//                if ($user->pid == 0 && $request->post('pid')) {
//                    $parent_user = User::find($request->post('pid'));
//                    if ($user->id != $parent_user->pid) {
//                        $user->pid = $request->post('pid');
//                    }
//                }
                $user->save();
            }
            $res=[
                'api_token' => $api_token,
//                'session_key'=> $login_res['session_key'],
                'openid'    =>  $login_res['openid'],
                'can_hexiao'=>1
            ];
            //todo  判断用户能否核销
            return $this->response(0,$res,'登录成功');
        }else {//授权失败
            return $this->response($login_res['status_code'],[],$login_res['message'],$login_res['errors']);
        }
    }
}
